<script setup lang="ts">
import { type FormInstance, Message, Modal, type RequestOption } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { Notification } from '@arco-design/web-vue'
import { useDownload, useForm } from '@/hooks'
import { CouponApi } from '@/apis'

const emit = defineEmits<{
  (e: 'change'): void
}>()
const { width } = useWindowSize()

const formRef = ref<FormInstance>()
const uploadFile = ref([])

const { form, resetForm } = useForm({
  importKey: null,
})

const dataResult = ref<CouponApi.CouponImportParseResp>({
  importKey: '',
  totalRows: 0,
  validRows: 0,
})

const visible = ref(false)

// 重置
const reset = () => {
  formRef.value?.resetFields()
  dataResult.value = {
    importKey: '',
    totalRows: 0,
    validRows: 0,
  }
  uploadFile.value = []
  visible.value = false
  resetForm()
}

const open = () => {
  reset()
  visible.value = true
}

// 下载模板
const downloadTemplate = () => {
  useDownload(() => CouponApi.downloadImportCouponTemplate())
}

// 上传解析导入数据
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController();
  (async function requestWrap() {
    const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
    onProgress(20)
    const formData = new FormData()
    formData.append(name as string, fileItem.file as Blob)
    try {
      const res = await CouponApi.parseImportCoupon(formData)
      dataResult.value = res
      Message.success('上传解析成功')
      onSuccess(res)
    } catch (error) {
      onError(error)
    }
  })()
  return {
    abort() {
      controller.abort()
    },
  }
}

// 执行导入
const save = async () => {
  try {
    if (!dataResult.value.importKey) {
      return false
    }
    form.importKey = dataResult.value.importKey
    await CouponApi.upload(form)
    Notification.info({
      title: '导入结果',
      content: '导入成功！',
    })
    // Message.success('导入成功')
    emit('change')
    visible.value = false
    return true
  } catch {
    return false
  }
}

const beforeRemove = (file) => {
  return new Promise((resolve) => {
    Modal.confirm({
      title: '提示',
      content: `确认删除 ${file.name}`,
      onOk: () => {
        uploadFile.value = []
        dataResult.value = {
          importKey: '',
          totalRows: 0,
          validRows: 0,
        }
        resolve(true)
      },
    })
  })
}

defineExpose({ open })
</script>

<template>
  <ProDrawer
    :visible="visible"
    title="导入优惠券"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 600 ? 600 : '100%'"
    ok-text="确认导入"
    cancel-text="取消导入"
    @before-ok="save"
    @cancel="reset"
  >
    <a-form ref="formRef" :model="form" size="large" auto-label-width>
      <a-alert v-if="!form.disabled" :show-icon="false" style="margin-bottom: 15px">
        数据导入请严格按照模板填写，格式要求和新增一致！
        <template #action>
          <a-button size="small" type="primary" @click="downloadTemplate">
            下载模板
          </a-button>
        </template>
      </a-alert>
      <fieldset>
        <legend>1.上传解析文件</legend>
        <div class="file-box">
          <a-upload
            draggable
            :custom-request="handleUpload"
            :limit="1"
            :show-retry-butto="false"
            :show-cancel-button="false" tip="仅支持xls、xlsx格式"
            :file-list="uploadFile"
            accept=".xls, .xlsx, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            @before-remove="beforeRemove"
          />
        </div>
        <div v-if="dataResult.importKey !== undefined">
          <div class="file-box">
            <a-space size="large">
              <a-statistic title="总计行数" :value="dataResult.totalRows" />
              <a-statistic title="正常行数" :value="dataResult.validRows" />
            </a-space>
          </div>
        </div>
      </fieldset>
    </a-form>
  </ProDrawer>
</template>

<style lang="scss" scoped>
fieldset {
  padding: 15px 15px 0 15px;
  margin-bottom: 15px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}

fieldset legend {
  color: rgb(var(--gray-10));
  padding: 2px 5px 2px 5px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}

.file-box {
  margin-bottom: 20px;
  margin-left: 10px;
}
</style>
